package com.biz.controller.basic;

import com.alibaba.fastjson.JSON;
import com.biz.model.Hmodel.basic.TGoodsBrand;
import com.biz.model.Hmodel.basic.TGoodsUnit;
import com.biz.model.Pmodel.User;
import com.biz.model.Pmodel.basic.PbaseStandard;
import com.biz.model.Pmodel.basic.PgoodsBrand;
import com.biz.model.Pmodel.basic.PgoodsUnit;
import com.biz.model.Pmodel.basic.PwxgoodsGroup;
import com.biz.service.basic.LogServiceI;
import com.biz.service.basic.PropertyServiceI;
import com.framework.controller.BaseController;
import com.framework.model.MessageBox;
import com.framework.model.Operation;
import com.framework.model.Pager;
import com.framework.model.Paging;
import com.framework.utils.Node;
import com.framework.utils.TreeBuilder;
import com.framework.utils.UuidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by ZK123 on 2017/10/11 0011.
 */
@Controller
@RequestMapping("/property")
public class PropertyController extends BaseController{

    @Autowired
    private PropertyServiceI propertyService;

    @Autowired
    private LogServiceI LogService;

    @InitBinder("pwxgoodsGroup")
    public void initBinderFormBean1(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("pwxgoodsGroup.");
    }

    @InitBinder("pbaseStandard")
    public void initBinderFormBean2(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("pbaseStandard.");
    }

    @RequestMapping("toBrand")
    public ModelAndView toBrand(ModelAndView mv){
        mv.setViewName("sys/property/brand");
        mv.addObject("test",":test");
        return mv;
    }

    @RequestMapping("showBrand")
    public void showBrand(HttpServletResponse response, HttpServletRequest request)throws Exception{
        //前端封装的查询参数
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("name", request.getParameter("name"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        int offset = Integer.parseInt(request.getParameter("offset"));

        Pager<PgoodsBrand> pager = new Pager();
        pager.setParameters(params);
        pager.setStartRecord(offset);
        pager.setPageSize(limit);

        pager = propertyService.showBrand(pager);

        Paging<PgoodsBrand> paging = new Paging<>();
        paging.setRows(pager.getExhibitDatas());
        paging.setTotal((long) pager.getRecordCount());

        writeJson(paging, response);
    }

    @RequestMapping("doSaveOrUpdateBrand")
    public void doSaveOrUpdateBrand(HttpServletResponse response, HttpServletRequest request,PgoodsBrand pgoodsBrand) {
        MessageBox mb = getBox();
        User user = (User) getShiroAttribute("userinfo");
        try {
            if(pgoodsBrand.getSource().equals("0")){
                //新增
                TGoodsBrand t=new TGoodsBrand();
                t.setId(UuidUtil.get32UUID());
                t.setName(pgoodsBrand.getName());
                propertyService.save(t);
                LogService.saveLog(getRequest().getRemoteAddr(),user.getId(), Operation.ADD,"新增品牌");
            }else{
                //更新
                TGoodsBrand t=propertyService.getById(pgoodsBrand.getId());
                t.setName(pgoodsBrand.getName());
                propertyService.update(t);
                LogService.saveLog(getRequest().getRemoteAddr(),user.getId(), Operation.UPDATE,"更新品牌");
            }
            mb.setSuccess(true);
        }catch (Exception e){
            mb.setSuccess(false);
            mb.setMsg(e.getMessage());
            e.printStackTrace();
        }
        writeJson(mb,response);
    }

    @RequestMapping("toAddOrEdit")
    public ModelAndView toAddOrEdit(String code,String type,ModelAndView mv){
        mv.addObject("source",type);
        TGoodsBrand t=new TGoodsBrand();
        if(type.equals("1")){
            t=propertyService.getById(code);
        }
        mv.addObject("tgoodsBrand",t);
        mv.setViewName("sys/property/brandDetail");
        return mv;
    }

    @RequestMapping("deBrandByIds")
    public void deBrandByIds(HttpServletResponse response, HttpServletRequest request,String ids) {
        MessageBox mb = getBox();
        User user = (User) getShiroAttribute("userinfo");
        try {
            mb=propertyService.deBrandByIds(ids);
            LogService.saveLog(getRequest().getRemoteAddr(),user.getId(), Operation.DELETE,"删除品牌");

        }catch (Exception e){
            mb.setSuccess(false);
            mb.setMsg(e.getMessage());
            e.printStackTrace();
        }
        writeJson(mb,response);
    }


    @RequestMapping("toUnit")
    public ModelAndView toUnit(ModelAndView mv){
        mv.setViewName("sys/property/unit");
        return mv;
    }


    @RequestMapping("showUnit")
    public void showUnit(HttpServletResponse response, HttpServletRequest request)throws Exception{
        //前端封装的查询参数
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("name", request.getParameter("name"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        int offset = Integer.parseInt(request.getParameter("offset"));

        Pager<PgoodsUnit> pager = new Pager();
        pager.setParameters(params);
        pager.setStartRecord(offset);
        pager.setPageSize(limit);

        pager = propertyService.showUnit(pager);

        Paging<PgoodsUnit> paging = new Paging<>();
        paging.setRows(pager.getExhibitDatas());
        paging.setTotal((long) pager.getRecordCount());

        writeJson(paging, response);
    }

    @RequestMapping("toAddOrEditUnit")
    public ModelAndView toAddOrEditUnit(String code,String type,ModelAndView mv)throws Exception{
        mv.addObject("source",type);
        TGoodsUnit t=new TGoodsUnit();
        if(type.equals("1")){
            t=propertyService.getUnitById(code);
        }
        mv.addObject("tgoodsUnit",t);
        mv.setViewName("sys/property/unitDetail");
        return mv;
    }


    @RequestMapping("doSaveOrUpdateUnit")
    public void doSaveOrUpdateUnit(HttpServletResponse response, HttpServletRequest request,PgoodsUnit pgoodsUnit) {
        MessageBox mb = getBox();
        User user = (User) getShiroAttribute("userinfo");
        try {
            mb=propertyService.doSaveOrUpdateUnit(pgoodsUnit);
            if(pgoodsUnit.getSource().equals("0")){
                LogService.saveLog(getRequest().getRemoteAddr(),user.getId(),Operation.ADD,"新增单位");
            }else{
                LogService.saveLog(getRequest().getRemoteAddr(),user.getId(),Operation.UPDATE,"编辑单位");
            }
        }catch (Exception e){
            mb.setSuccess(false);
            mb.setMsg(e.getMessage());
            e.printStackTrace();
        }
        writeJson(mb,response);
    }

    @RequestMapping("deUnitByIds")
    public void deUnitByIds(HttpServletResponse response, HttpServletRequest request,String ids) {
        MessageBox mb = getBox();
        User user = (User) getShiroAttribute("userinfo");
        try {
            mb=propertyService.deUnitByIds(ids);
            LogService.saveLog(getRequest().getRemoteAddr(),user.getId(),Operation.DELETE,"删除单位");
        }catch (Exception e){
            mb.setSuccess(false);
            mb.setMsg(e.getMessage());
            e.printStackTrace();
        }
        writeJson(mb,response);
    }

    @RequestMapping("toGroupTag")
    public ModelAndView toGroupTag(ModelAndView mv){
        mv.setViewName("sys/property/groupTag");
        return mv;
    }

    /**
     * 获取分组标签
     */
    @RequestMapping("getAllGroupTagList")
    public void getAllGroupTagList(HttpServletResponse response)throws Exception{
        List<PwxgoodsGroup> orgList=propertyService.getAllGroupTagList("1");

        //将查询出来的list进行树化
        TreeBuilder tb = new TreeBuilder();
        List<Node> allNodes = new ArrayList<Node>();
        for(int i=0;i<orgList.size();i++){
            //参数说明：
            allNodes.add(new Node(orgList.get(i).getId(),orgList.get(i).getPid(),orgList.get(i).getName(),orgList.get(i).getNote(),orgList.get(i).getIcon()));
        }
        List<Node> roots = TreeBuilder.buildListToTree(allNodes);
        String json = JSON.toJSONString(roots);
        writeJson(json, response);
    }


    @RequestMapping("toGroupTagDetail")
    public ModelAndView toGroupTagDetail(ModelAndView mv,String type,String state,String id,String ppid)throws Exception{
        PwxgoodsGroup pwxgoodsGroup=new PwxgoodsGroup();
        List<PwxgoodsGroup> list=propertyService.getAllGroupTagList("0");
        if(state.equals("0")){
            //新增
        }else{
            //编辑
            pwxgoodsGroup=propertyService.getGroupTagDetail(type,id);
        }
        mv.addObject("pwxgoodsGroup",pwxgoodsGroup);
        mv.addObject("type",type);
        mv.addObject("id",id);
        mv.addObject("state",state);
        mv.addObject("list",list);
        mv.addObject("ppid",ppid);
        mv.setViewName("sys/property/groupTag_edit");
        return mv;
    }

    @RequestMapping("doSaveOrUpdateGroupTag")
    public void doSaveOrUpdateGroupTag(HttpServletResponse response, HttpServletRequest request,PwxgoodsGroup pwxgoodsGroup)throws Exception {
        MessageBox mb = getBox();
        User user = (User) getShiroAttribute("userinfo");
        try {
            mb=propertyService.doSaveOrUpdateGroupTag(pwxgoodsGroup);
            if(pwxgoodsGroup.getState().equals("0")){
                //新增
                LogService.saveLog(getRequest().getRemoteAddr(),user.getId(),Operation.ADD,"新增分组标签");
            }else{
                //编辑
                LogService.saveLog(getRequest().getRemoteAddr(),user.getId(),Operation.UPDATE,"编辑分组标签");
            }
        }catch (Exception e){
            mb.setSuccess(false);
            mb.setMsg(e.getMessage());
            e.printStackTrace();
        }
        writeJson(mb,response);
    }

    @RequestMapping("delgroupTag")
    public void delgroupTag(HttpServletResponse response,String id,String pid)throws Exception {
        MessageBox mb = getBox();
        User user = (User) getShiroAttribute("userinfo");
        try {
            mb=propertyService.delgroupTag(id,pid);
            LogService.saveLog(getRequest().getRemoteAddr(),user.getId(),Operation.DELETE,"删除分组标签");
        }catch (Exception e){
            mb.setSuccess(false);
            mb.setMsg(e.getMessage());
            e.printStackTrace();
        }
        writeJson(mb,response);
    }


    @RequestMapping("toStandard")
    public ModelAndView toStandard(ModelAndView mv){
        mv.setViewName("sys/property/standard");
        return mv;
    }

    /**
     * 获取商品属性
     */
    @RequestMapping("getAllStandardList")
    public void getAllStandardList(HttpServletResponse response)throws Exception{
        List<PbaseStandard> orgList=propertyService.getAllStandardList("0");

        //将查询出来的list进行树化
        TreeBuilder tb = new TreeBuilder();
        List<Node> allNodes = new ArrayList<Node>();
        for(int i=0;i<orgList.size();i++){
            //参数说明：
            allNodes.add(new Node(orgList.get(i).getId(),orgList.get(i).getPid(),orgList.get(i).getText(),orgList.get(i).getType()));
        }
        List<Node> roots = TreeBuilder.buildListToTree(allNodes);
        String json = JSON.toJSONString(roots);
        writeJson(json, response);
    }


    /**
     * 跳转sku详情页
     * @param mv
     * @param type
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("toStandardDetail")
    public ModelAndView toStandardDetail(ModelAndView mv,String type,String id)throws Exception{
        List<PbaseStandard> list=propertyService.getAllStandardList("1");
        PbaseStandard pbaseStandard=new PbaseStandard();
        if(type.equals("1")){
            pbaseStandard=propertyService.getPbaseStandard(id);
        }
        mv.addObject("pbaseStandard",pbaseStandard);
        mv.addObject("type",type);
        mv.addObject("list",list);
        mv.setViewName("sys/property/standard_edit");
        return mv;
    }

    /**
     * 新增更新sku表
     * @param response
     * @param request
     * @param pbaseStandard
     * @throws Exception
     */
    @RequestMapping("doSaveOrUpdateStandard")
    public void doSaveOrUpdateStandard(HttpServletResponse response, HttpServletRequest request,PbaseStandard pbaseStandard)throws Exception {
        MessageBox mb = getBox();
        User user = (User) getShiroAttribute("userinfo");
        try {
            mb=propertyService.doSaveOrUpdateStandard(pbaseStandard);
            if(pbaseStandard.getType().equals("0")){
                //新增
                LogService.saveLog(getRequest().getRemoteAddr(),user.getId(),Operation.ADD,"新增商品sku");
            }else{
                //编辑
                LogService.saveLog(getRequest().getRemoteAddr(),user.getId(),Operation.UPDATE,"编辑商品sku");
            }
        }catch (Exception e){
            mb.setSuccess(false);
            mb.setMsg(e.getMessage());
            e.printStackTrace();
        }
        writeJson(mb,response);
    }

    @RequestMapping("delStandard")
    public void delStandard(HttpServletResponse response,String id)throws Exception {
        MessageBox mb = getBox();
        User user = (User) getShiroAttribute("userinfo");
        try {
            mb=propertyService.delStandard(id);
            LogService.saveLog(getRequest().getRemoteAddr(),user.getId(),Operation.DELETE,"删除商品sku");
        }catch (Exception e){
            mb.setSuccess(false);
            mb.setMsg(e.getMessage());
            e.printStackTrace();
        }
        writeJson(mb,response);
    }

}
